package com.student.manage.controller;


import com.student.manage.annotation.RepeatSubmit;
import com.student.manage.aop.RepeatSubmitAspect;
import com.student.manage.entity.User;
import com.student.manage.entity.model.UpdateResult;
import com.student.manage.service.IUserService;
import com.student.manage.util.DigestUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    IUserService userService;

    @RequestMapping("/list")
    public String index(Model model) {

        List<User> list = userService.list();
        model.addAttribute("list", list);
        return "user_list";
    }


    @RequestMapping("/edit.html")
    public String edit(Model model, @RequestParam Integer id, HttpSession session) {
        User user = userService.getById(id);
        model.addAttribute("user", user);
        session.setAttribute(RepeatSubmitAspect.REPEAT_SUBMIT, DigestUtils.md5(LocalDateTime.now().toString()));
        return "user_edit";
    }

    @PostMapping("/edit")
    @RepeatSubmit(fallback = "redirect:/user/edit.html", paramNames = "id")
    public String edit(Model model, User user) {
        UpdateResult updateResult = userService.updateByIdSelective(user);

        if (updateResult.isSuccess()) {
            return "update_success";
        }
        model.addAttribute("updateResult", updateResult);
        model.addAttribute("user", user);

        return "forward:/user/edit.html?id=" + user.getId();

    }


    @RequestMapping("/delete")
    public String deleteUser(Model model, @RequestParam Integer id) {
        userService.deleteById(id);
        return "redirect:/user/list";
    }
}
